using System;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Controls.Primitives;

namespace Making.Avalonia.Views;

public partial class MainView : UserControl
{
    public MainView(IServiceProvider serviceProvider)
    {
        InitializeComponent();
        
        // 为缩放滑块添加事件处理器
        ZoomSlider.ValueChanged += OnZoomSliderValueChanged;
    }

    private void OnBackClick(object? sender, RoutedEventArgs e)
    {
        WebView.GoBack();
    }

    private void OnForwardClick(object? sender, RoutedEventArgs e)
    {
        WebView.GoForward();
    }

    private void OnReloadClick(object? sender, RoutedEventArgs e)
    {
        WebView.Reload();
    }

    private void OnNavigateClick(object? sender, RoutedEventArgs e)
    {
        var url = UrlTextBox.Text;

        if (!string.IsNullOrWhiteSpace(url))
        {
            if (url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
                url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
            {
                WebView.Navigate(new Uri(url));
            }
            else
            {
                WebView.Navigate(new Uri($"http://{url}"));
            }
        }
    }

    private void OnZoomSliderValueChanged(object? sender, RangeBaseValueChangedEventArgs e)
    {
        if (sender is Slider slider)
        {
            var zoomValue = slider.Value;
            
            // 更新缩放标签文本
            ZoomLabel.Text = $"{zoomValue:F0}%";
            
            // 设置WebView的缩放因子 (滑块值是百分比，需要转换为小数)
            WebView.ZoomFactor = zoomValue / 100.0;
        }
    }
}